package com.winhxd.b2c.customer.service.impl;

import com.winhxd.b2c.common.cache.Cache;
import com.winhxd.b2c.common.constant.BusinessCode;
import com.winhxd.b2c.common.constant.CustomerConstant;
import com.winhxd.b2c.common.domain.ResponseResult;
import com.winhxd.b2c.common.domain.customer.condition.InvitationRecordCondition;
import com.winhxd.b2c.common.domain.customer.enums.CustomerUserLevelEnum;
import com.winhxd.b2c.common.domain.customer.model.CustomerInvitationRecord;
import com.winhxd.b2c.common.domain.customer.model.CustomerUserInfo;
import com.winhxd.b2c.common.domain.system.user.condition.CheckUserCondition;
import com.winhxd.b2c.common.domain.system.user.dto.SysUserDTO;
import com.winhxd.b2c.common.domain.system.user.model.SysUser;
import com.winhxd.b2c.common.domain.system.user.vo.UserInfo;
import com.winhxd.b2c.common.exception.BusinessException;
import com.winhxd.b2c.common.feign.system.UserServiceClient;
import com.winhxd.b2c.common.mq.MQHandler;
import com.winhxd.b2c.common.mq.StringMessageListener;
import com.winhxd.b2c.common.util.DateUtil;
import com.winhxd.b2c.common.util.JsonUtil;
import com.winhxd.b2c.customer.service.CustomerLoginService;
import com.winhxd.b2c.customer.service.CustomerService;
import com.winhxd.b2c.customer.service.InvitationRecordService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 订单消费者
 * @author: liuhanning
 * @create: 2019-01-11 15:09
 **/
public class CustomerMessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(CustomerMessageHandler.class);

    @Autowired
    private Cache cache;

    @Autowired
    private UserServiceClient userServiceClient;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private CustomerLoginService  customerLoginService;

    @Autowired
    private InvitationRecordService invitationRecordService;

    /**
     * 初始化 后台登录账号
     * @param customerUser
     */
    @Transactional(rollbackFor = Exception.class)
    @StringMessageListener(value = MQHandler.INIT_SYS_USER)
    public void saveUserService(String customerUser) {
        logger.info("MQ-CustomerMessageHandler-绑定手机号初始化后台登录账号：{}",customerUser);
        if (StringUtils.isBlank(customerUser)) {
            throw new BusinessException(BusinessCode.CODE_1026);
        }
        CustomerUserInfo userInfo = JsonUtil.parseJSONObject(customerUser,CustomerUserInfo.class);
        SysUser sysUser;
        //初始化后台登录账号
        CheckUserCondition condition = new CheckUserCondition();
        condition.setCustomerId(userInfo.getParentId());
        ResponseResult<SysUser> result = userServiceClient.getSysUserByCondition(condition);
        if(result.getCode()!=0){
            throw new BusinessException(BusinessCode.CODE_1001);
        }
        sysUser = result.getData();
        logger.info("MQ-CustomerMessageHandler-绑定手机号初始化后台登录账号--获取上级员工的信息：{}",JsonUtil.toJSONString(sysUser));
        if(null==sysUser){
            throw new BusinessException(BusinessCode.CODE_1026);
        }
        boolean bool = customerService.saveSystemUser(userInfo,sysUser,userInfo.getId(),userInfo.getUpdatedByName());
        logger.info("MQ-CustomerMessageHandler-创建账号成功！{}--{}",userInfo.getCustomerMobile(),bool);
    }

    /**
     * 保存邀请会员原始关系
     * @param record
     */
    @Transactional(rollbackFor = Exception.class)
    @StringMessageListener(value = MQHandler.INVITATION_RECORD)
    public void saveInvitationRecordService(String record) {
        logger.info("MQ-CustomerMessageHandler-保存邀请会员原始关系：{}",record);
        if (StringUtils.isBlank(record)) {
            throw new BusinessException(BusinessCode.CODE_1026);
        }
        CustomerInvitationRecord invitationRecord = JsonUtil.parseJSONObject(record,CustomerInvitationRecord.class);
        invitationRecordService.saveInvitationRecord(invitationRecord);
    }

    /**
     * 会员升级二级店铺后，更新原始会员的ParentId
     * @param customerId
     */
    @Transactional(rollbackFor = Exception.class)
    @StringMessageListener(value = MQHandler.UPDATE_CUSTOMER_PARENT_ID)
    public void updateCustomerParentId(String customerId) {
        logger.info("MQ-CustomerMessageHandler-换绑更新原始会员的ParentId：{}",customerId);
        if (StringUtils.isBlank(customerId)) {
            throw new BusinessException(BusinessCode.CODE_1026);
        }
        InvitationRecordCondition recordCondition= new InvitationRecordCondition();
        recordCondition.setMasterId(Long.parseLong(customerId));
        //把会员原来邀请过去的用户更新到自己的下面
        customerService.modifyCustomerParentIdById(recordCondition);
    }

    /**
     * 统计当日
     * @param customerId
     */
    @Transactional(rollbackFor = Exception.class)
    @StringMessageListener(value = MQHandler.TODAY_USER_NUMBER)
    public void cacheTodayUserCount(String customerId) {
        logger.info("MQ-CustomerMessageHandler-统计当日用户的数量customerId：{}",customerId);
        if (StringUtils.isBlank(customerId)) {
            throw new BusinessException(BusinessCode.CODE_1026);
        }
        CustomerUserInfo customerUserInfo = customerLoginService.getCustomerUserInfoById(Long.parseLong(customerId));
        if(customerUserInfo!=null) {
            if(CustomerUserLevelEnum.CUSTOMER_LEVEL_0.getCode().intValue()==customerUserInfo.getLevel().intValue()){
                customerUserInfo.setAccessTime(new Date());
                customerLoginService.updateCustomerInfo(customerUserInfo);
                String key = CustomerConstant.USER_TODAY_VISIT_COUNT + customerUserInfo.getParentId();
                long end = DateUtil.getEndDate(new Date()).getTime();
                long locl = System.currentTimeMillis();
                int seconds = Integer.parseInt(String.valueOf((end - locl)/1000));
                Map<String, String> map;
                if (cache.exists(key)) {
                    map = cache.hgetAll(key);
                    if (!map.containsKey(customerId)) {
                        map.put(customerId, customerId);
                    }
                    cache.hmset(key, map);
                    cache.expire(key, seconds);
                } else {
                    map = new HashMap<>(10);
                    map.put(customerId, customerId);
                    cache.hmset(key, map);
                    cache.expire(key, seconds);
                }
                logger.info("MQ-CustomerMessageHandler-统计当日用户的数量customerId：{}--------{}-----{}",customerId,JsonUtil.toJSONString(map),seconds);
            }
        }
    }
}
